package dahuiji.common.core;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;

import dahuiji.common.dao.BaceDao;
import dahuiji.common.entity.Line;
import dahuiji.common.entity.LineRecord;
import dahuiji.common.entity.User;
import dahuiji.common.sysdata.CommonData;
import dahuiji.common.util.Constants;
import dahuiji.common.util.SendMail;

/**
 * 这个类提供通知用户服务
 * 
 * @author Administrator
 * 
 */
public class NoticeUser {
	private LineData lineData;
	private SendMail sendMail;
	private BaceDao baceDao;
	private StringBuilder content;
	private DateCaozuo dateCaozuo = new DateCaozuo();

	/**
	 * 通知用户，type0，是具体日期的
	 * 
	 * @param id
	 * @param type
	 *            type是刚通知还是之前也通知过
	 * @return
	 */
	public boolean noticeUserOneDate(Line line, short type, int pr) {
		sendMail = new SendMail();
		content = new StringBuilder();
		baceDao = new BaceDao();
		lineData = new LineData();
		User user = (User) baceDao.getEntity(User.class, line.getUserId());
		String hangxian = line.getFromCity() + "to" + line.getToCity() + "时间："
				+ line.getfDate();// 用户检测的航线
		LineRecord lineRecord = null;
		if (type == Constants.FIRST_NOTICE_USER) {// 第一次通知
			
			lineData.updateLine(line, pr);// 更新这条线路，设置发送过，保存记录
			content.append(Constants.TE_YES_MSG + "航线信息：" + hangxian);
			content.append("特价信息,");
			content.append("价格:" + pr);
			sendMail.send(Constants.STMP, Constants.MY_EMAIL,
					Constants.MY_EMAIL_P, user.getEmail(),
					Constants.TE_YES_SUB, content.toString());
		} else if (type == Constants.NOT_FIRST_NOTICE_USER) {// 不是第一通知
			// 判断这个价是否低于历史记录
			int min = 0;
			List<LineRecord> lRecords = CommonData.allLineRecord.get(line
					.getId());// 根据id得到历史记录
			int length = lRecords.size();
			min = lRecords.get(0).getPrice();
			// 找到最小值
			for (int i = 0; i < length; i++) {
				if (lRecords.get(i).getPrice() < min) {
					min = lRecords.get(i).getPrice();
				}
			}
			if (pr < min) {// 现在这个价比记录里的最小值小，通知用户
				content.append(Constants.TE_YES_MSG);
				content.append("我们再一次发现了特价机票，信息如下：");
				content.append("航线信息,");
				content.append(hangxian);
				content.append("特价信息,");
				content.append("价格:" + pr);
				lineRecord = new LineRecord();
				lineRecord.setDate(dateCaozuo.getNowDate());
				lineRecord.setLindId(line.getId());
				lineRecord.setPrice((short) pr);
				lineData.addLineR(lineRecord);
				sendMail.send(Constants.STMP, Constants.MY_EMAIL,
						Constants.MY_EMAIL_P, user.getEmail(),
						Constants.TE_YES_SUB, content.toString());
			}
		}

		return true;
	}

	/**
	 * 用户的航线是一段时间的
	 * 
	 * @param line
	 * @param type
	 * @param pr
	 * @param date
	 */
	public void noticeUserNotOneDay(Line line, List<LineRecord> lineRecords) {
		sendMail = new SendMail();
		content = new StringBuilder();
		baceDao = new BaceDao();
		lineData = new LineData();
		User user = (User) baceDao.getEntity(User.class, line.getUserId());
		String hangxian = line.getFromCity() + "to" + line.getToCity() + "时间："
				+ line.getfDate() + "--" + line.getToDate();// 用户检测的航线
		// 如果是第一发送通知，好办，save记录，构建邮件内容，发送邮件
		if (line.getFlag() == Constants.LINE_SEND_NOTICE_NO) {
			content.append(Constants.TE_YES_MSG);
			content.append("信息如下:");
			for (int i = 0; i < lineRecords.size(); i++) {
				content.append(lineRecords.get(i).getLineDate() + "-->"
						+ lineRecords.get(i).getPrice());
				baceDao.save(lineRecords.get(i));//保存记录

			}
			sendMail.send(Constants.STMP, Constants.MY_EMAIL,
					Constants.MY_EMAIL_P, user.getEmail(),
					Constants.TE_YES_SUB, content.toString());
			line.setFlag(Constants.LINE_SEND_NOTICE_YES);// 标记已经发送过
			baceDao.saveOrUpdate(line);//标记发送过
		} else if (line.getFlag() == Constants.LINE_SEND_NOTICE_YES) {// 通知过了，这就麻烦了
			// 1,从内存中得到所有的记录，然后得到用户检测的具体日期，得到这些天的历史记录，在找最小价格，如果刚检测到的特价比历史记录里的最小还低，通知用户
			long das = HowManyDas(line.getfDate(), line.getToDate());// 计算相差几天
			Map<Date, List<LineRecord>> dayMa = new HashMap<Date, List<LineRecord>>();
			List<LineRecord> lRecords = CommonData.allLineRecord.get(line
					.getId());// 根据id得到历史记录
			List<LineRecord> lrDays = null;// 以日期来存历史列表
			LineRecord lineR = null;
			int lRLength = lRecords.size();// 历史记录得长度
			Date da = line.getfDate();// 中间变量存日期加，初始化是开始的那天
			das = das + 1;// 之所以加1是因为监测的也包含当天
			for (int i = 0; i < das; i++) {
				lrDays = new ArrayList<LineRecord>();
				for (int j = 0; j < lRLength; j++) {
					if (lRecords.get(j).getLineDate().equals(da)) {
						lrDays.add(lRecords.get(j));
					}
				}
				try {
					da=dateCaozuo.addTown(da, 1);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}// 天加1
				dayMa.put(da, lrDays);
			}
			// 便利得到的特价列表，然后根据时间来拿
			int newLRLength = lineRecords.size();
			List<LineRecord> dayLRlist = null;
			content.append(Constants.TE_YES_MSG);
			content.append("航线信息如下");
			boolean ifsend = false;
			for (int i = 0; i < newLRLength; i++) {
				dayLRlist = dayMa.get(lineRecords.get(i).getLineDate());// 根据时间来拿历史记录
				
				if(dayLRlist!=null){//这一天有记录
					int min = dayLRlist.get(0).getPrice();
					for (int j = 0; j < dayLRlist.size(); j++) {
						if (min < dayLRlist.get(j).getPrice()) {
							min = dayLRlist.get(j).getPrice();// 找最小值
						}
					}
					// 如果最新发现的最小值比历史记录里的最小小，通知用户吧
					if (lineRecords.get(i).getPrice() < min) {
						
						ifsend = true;
						content.append(lineRecords.get(i).getLineDate() + "-->"
								+ lineRecords.get(i).getPrice());
						baceDao.save(lineRecords.get(i));

					}
				}else{
					//这一天的记录是空的
					ifsend = true;
					content.append(lineRecords.get(i).getLineDate() + "-->"
							+ lineRecords.get(i).getPrice());
					baceDao.save(lineRecords.get(i));
				}
				
			}
			if (ifsend) {
				sendMail.send(Constants.STMP, Constants.MY_EMAIL,
						Constants.MY_EMAIL_P, user.getEmail(),
						Constants.TE_YES_SUB, content.toString());
			}

		}

	}

	/**
	 * 通知用户这条记录是错的
	 * 
	 * @param line
	 */
	public void lineWrong(Line line) {
		sendMail = new SendMail();
		baceDao = new BaceDao();
		content = new StringBuilder();
		lineData = new LineData();
		User user = (User) baceDao.getEntity(User.class, line.getUserId());
		String hangxian = null;
		if (line.getTpye() == Constants.LINE_TYPE_ONE) {
			hangxian = line.getFromCity() + "to" + line.getToCity() + "时间："
					+ line.getfDate();// 用户检测的航线
		} else {
			hangxian = line.getFromCity() + "to" + line.getToCity() + "时间："
					+ line.getfDate() + "--" + line.getToDate();// 用户检测的航线
		}

		content.append("航信信息" + hangxian);
		sendMail.send(Constants.STMP, Constants.MY_EMAIL, Constants.MY_EMAIL_P,
				user.getEmail(), Constants.LINE_WRONG_SUB,
				Constants.LINE_WRONG_MSG + content.toString());
		line.setFlag(Constants.LINE_SEND_NOTICE_YES);
		line.setStatus(Constants.LINE_RIGHT_NO);
		baceDao.update(line);
	}

	/**
	 * 计算这两个日期相差几天
	 * 
	 * @param f
	 * @param t
	 * @return
	 */
	public Long HowManyDas(Date f, Date t) {
		Calendar fDate = Calendar.getInstance();
		Calendar tDate = Calendar.getInstance();
		fDate.setTime(f);//
		tDate.setTime(t);// 
		long timeNow = tDate.getTimeInMillis();
		long timeOld = fDate.getTimeInMillis();
		return (timeNow - timeOld) / (1000 * 60 * 60 * 24);
	}

}
